<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 10-14/0014
 * Time: 13:56
 * 产品同步
 * uu_land表：salerid,apply_did，terminal字段禁止更改
 * 返回：
 * 100:平台账号未绑定
 * 101:数据不存在
 * 102:属性冲突
 * 103:参数错误
 */
header('Content-type: application/x-javascript');
define('ROOT_PATH','/var/www/html/new/d/');
define('FX_PATH', ROOT_PATH.'class/');

define('ORIGIN_12301', 1);
define('ORIGIN_16U', 2);


define('CUR_ORIGIN', ORIGIN_12301);//当前平台1票付通，2先行

define('REQUEST_URL', 'http://www.16u.cc/');//请求地址
//define('REQUEST_URL', 'http://www.12301.cc/');//请求地址

//$_ac = '16ucom';
//$_pw = 'c33367701511b4f6020ec61ded352059';

//include ROOT_PATH . 'conf/le.je';
//include ROOT_PATH . 'conf/trans.le.je';//先行数据库连接

include ROOT_PATH . 'common/func.inc.php';
include FX_PATH . 'Product.class.php';
include FX_PATH . 'ProductSync.class.php';
include FX_PATH . 'SoapInit.class.php';
include FX_PATH . 'MemberAccount.class.php';
include FX_PATH . 'Sync.class.php';

$date_now = Sync::now();

Sync::writeLog($date_now . '|' .json_encode($_REQUEST), Sync::LOG_DIR . 'request.log');

$token = $_GET['token'];
unset($_GET['token']);

//判断是否为同源请求
if (!isset($_SESSION['memberID'])) {
    if ($token != md5('pft12301'.json_encode($_GET).'16u')) {
        Sync::writeLog(Sync::now() . '|验证失败,request=' . json_encode($_GET),
            Sync::LOG_DIR . 'access_denied.log');
        exit('403');
    }
}

$dbArr = Sync::GetMulDB();
//include 'Sync.php';

$le         = $dbArr['le'];
$le_trans   = $dbArr['trans_le'];


$action = safetxt($_REQUEST['action']);
//需要判定的属性，如果下列属性有设置(不等于默认值)，则无法同步！


switch($action) {
    case 'bind_account':
        $account = safetxt($_REQUEST['account']);
        $pwd     = safetxt($_REQUEST['pwd']);
        $mid     = $_SESSION['memberID'];
        if(!$mid) {
            $ret = array('status'=>'fail','msg'=>'登录超时,请刷新页面重新登陆');
        }
        else {
            $ret = Sync::BindAccount($mid, $account, $pwd);
        }
        echo json_encode($ret);
        break;
    //TODO::land表同步，编辑信息时也往这个表写数据
    case 'sync_land':
        $mid  = $_SESSION['memberID'];
        $lid  = intval($_REQUEST['lid']);
        //TODO::STEP 1,检测供应商账号是否已经绑定
        $sync_apply_did = Sync::Auth($mid);
        //TODO::STEP 2,检测产品属性
        $attr_ret = Sync::AttrChk($le, 'uu_land', $lid);
        if ($attr_ret['status']!='ok') {
            exit(json_encode($attr_ret));
        }
        //TODO::判断是否已经同步过（取消同步的）
        $sql = "SELECT sync_status,sync_id FROM uu_land WHERE id=$lid LIMIT 1";
//        echo $sql;
        $le->query($sql);
        $le->fetch_assoc();
        if ($le->f('sync_status')>2) {
            $res = Sync::ReSync($mid, $lid);
            echo json_encode($res);
            exit;
        }
        //TODO::STEP 3,检测产品是否已经同步
        $sql = "SELECT id FROM sync_data WHERE tbname='uu_land' and `col_id`=$lid LIMIT 1";
//        echo $sql;
        $le_trans->query($sql);
        $le_trans->fetch_assoc();
        $request_array  = array(
            'action' => $le_trans->f('id') ? 'update_land':'create_land',
            'lid'    => $lid,
            'mid'    => $sync_apply_did,
        );
//        print_r($request_array);
//        exit;
        $res = Sync::Notify($request_array);
        echo $res;
        break;
    case 'create_land':
        $lid = intval($_REQUEST['lid']);
        $mid = intval($_REQUEST['mid']);
        $ret = Sync::CreateLand($lid, $mid);
        $json = json_encode($ret);
        if($_REQUEST['callback']) {
            //JSONP
            $callBack = $_REQUEST['callback'];
            echo "$callBack({$json})";
        } else {
            echo $json;
        }
        break;
    case 'update_land':
        $lid  = intval($_GET['lid']);
        $mid  = intval($_GET['mid']);

        //TODO::获取还未同步的更新数据,uu_land表修改，记录的是字段名而不是值
        $chgArr = Sync::GetSyncLog($le_trans, 'uu_land', $lid, Sync::ORIGIN_16U);
//        print_r($chgArr);
//        exit;
        if (!count($chgArr)) {
            $logWord = "$date_now|没有数据更新;票付通lid={$lid}";
            Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_land_log.log');
            return false;
        }
        foreach ($chgArr as $logId=>$arr) {
            $chg_new_arr = explode(',', $arr['chg_new']);
            $cols = array_diff($chg_new_arr, array_keys(Sync::$AttrToChk[Sync::ORIGIN_16U]['uu_land']));
            if (!count($cols)) {
                exit('{"code":"101","msg":"不存在修改记录"}');
            }
            $colStr = implode(',', $cols);
            $sqlGetTransData = "SELECT {$colStr} FROM uu_land WHERE id={$lid} AND apply_did={$mid}";
            $le_trans->query($sqlGetTransData);
            $data = $le_trans->fetch_assoc();

            if (isset($data['imgpath'])) {
                $data['imgpath'] = 'http://www.16u.cc/' . $data['imgpath'];
            }
            if (isset($data['apply_did'])) {
                unset($data['apply_did']);
            }
            if (!$data) {
                Sync::ChgSyncStatus($le, $logId, Sync::SYNC_FAIL);
                echo '{"code":"101","msg":"数据不存在"}';
                continue;
            }
//            print_r($data);
//            echo $arr['sync_id'];
//            exit;
            $product = new \pft\Prod\Product($le);
            $update_res = $product->UpdateScenery($data, $arr['sync_id']);
            var_dump($update_res);
            if ($update_res['errcode'] == 1000) {
                $logWord = $date_now . "|同步产品OK,先行lid={$arr['col_id']},票付通lid={$arr['sync_id']}" .
                    ",同步记录ID={$chgArr['id']}";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_update_land.log');
                Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_OK);
            } else {
                $logWord = $date_now . "|同步产品FAIL,先行lid={$arr['col_id']},票付通lid={$arr['sync_id']}" .
                    ",同步记录ID={$chgArr['id']}";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_update_land.err');
                Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_FAIL);
            }
        }
        break;
    case 'update_land_status':
        //TODO::设置产品状态
        $lid  = intval($_GET['lid']);
        $mid  = intval($_GET['mid']);

        $chgArr = Sync::GetSyncLog($le_trans, 'uu_land', $lid, Sync::ORIGIN_16U);
        if (!count($chgArr)) {
            $logWord = "$date_now|没有数据更新;票付通lid={$lid}";
            Sync::writeLog($logWord, Sync::LOG_DIR . 'update_land_status.log');
            return false;
        }
        foreach ($chgArr as $logId=>$arr) {
            $product = new \pft\Prod\Product($le);
            $update_res = $product->SetSceneryState($arr['sync_id'], $arr['chg_new']);
            if ($update_res['status']=='ok' ) {
                $logWord = $date_now . "|同步产品OK,先行lid={$arr['sync_id']},票付通lid={$arr['col_id']}".
                    ",同步记录ID={$chgArr['id']}";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'update_land_status.log');
                Sync::ChgSyncStatus($le, $logId, Sync::SYNC_OK);
            }
            else {
                $logWord = $date_now."|同步产品FAIL,先行lid={$arr['sync_id']},票付通lid={$arr['col_id']}".
                    ",同步记录ID={$chgArr['id']}";
                Sync::writeLog($logWord, Sync::LOG_DIR .'update_land_status.err');
                Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_FAIL);
            }
        }
        break;
    case 'sync_ticket':
        //TODO::同步门票
        if(!$_SESSION['memberID']) {
            $ret = array('status'=>'fail','msg'=>'登录超时,请刷新页面重新登陆');
        }
        $tid = intval($_REQUEST['tid']);
        $chk_ret = Sync::AttrChk($le, 'uu_jq_ticket', $tid,'','', Sync::ORIGIN_12301);
        if ($chk_ret['status']!='ok') {
            echo json_encode($chk_ret);
            exit;
        }
        $sqlGetLandId = "SELECT l.sync_id as lid FROM uu_land l LEFT JOIN uu_jq_ticket t ON t.landid=l.id WHERE t.id=$tid LIMIT 1";
        $le->query($sqlGetLandId);
        $le->fetch_assoc();
        $lid = $le->f('lid');
//
        $sql = "SELECT id FROM sync_data WHERE tbname='uu_jq_ticket' and `col_id`=$tid LIMIT 1";
        $le->query($sql);
        $le->fetch_assoc();
        $sync_id = $le->f('id');
        $request_action = $sync_id ? 'update_ticket':'create_ticket';

        //通知同步
        Sync::Notify(
            array(
                'action'=> $request_action,
                'lid'   => $lid,
                'tid'   => $tid,
                'mid'   => $_SESSION['memberID'],
            )
        );
        break;
    case 'create_ticket':
        $landid        = intval($_REQUEST['sync_id']);//当前平台的landid
        $sync_tid      = intval($_REQUEST['tid']);
        $mid           = intval($_REQUEST['mid']);
        $apply_did     = Sync::Auth($mid, 1);
        $ret = Sync::CreateTicket($landid, $sync_tid, $apply_did, $mid, $dbArr, 1, 1);
        echo json_encode($ret);
        break;
    case 'update_ticket':
        $sync_tid       = intval($_REQUEST['tid']);//扩展表ID
        $sync_apply_did = intval($_REQUEST['mid']);//

        $apply_did      = Sync::Auth($sync_apply_did, 1);
        $date_now       = Sync::now();
        $dataTicketUnSync = Sync::GetSyncLog($le_trans, 'uu_jq_ticket', $sync_tid, Sync::ORIGIN_16U);
//        print_r($dataTicketUnSync);exit;
        Sync::writeLog($date_now .'|' .json_encode($dataTicketUnSync), Sync::LOG_DIR . 'debug.log');
        //$product = new ProductSync($le);
        if (!count($dataTicketUnSync)) {
            exit;
        }
        $sqlId = "SELECT id FROM uu_jq_ticket WHERE sync_id={$sync_tid} AND apply_did={$apply_did} AND sync_status=2  LIMIT 1";
        $le->query($sqlId);
        $le->fetch_assoc();
        $tid = $le->f('id');
        if (!$tid) {
            $logWord = "{$date_now}|{$sqlId}|记录不存在";
            Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_ticket_log.err');
            continue;
        }
        foreach ($dataTicketUnSync as $logId=>$row) {
            //col_id
            $sqlUpdate = "UPDATE uu_jq_ticket SET `{$row['col']}`='{$row['chg_new']}' WHERE id=$tid AND sync_status=2 LIMIT 1";
//            echo $sqlUpdate . PHP_EOL;
            Sync::writeLog($date_now . '|'.$sqlUpdate, Sync::LOG_DIR . 'sync_ticket_log.sql');
            if ($le->query($sqlUpdate)) {
                $logWord = "{$date_now}|同步票类成功|原始tid={$row['col_id']},更新ID:{$tid},记录主键id={$logId}";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_ticket_log.log');
                Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_OK, $tid);
            }
        }
        break;
    case 'update_land_f':
        $sync_tid       = intval($_REQUEST['tid']);//扩展表ID
        $sync_apply_did = intval($_REQUEST['mid']);//
        //todo::更新同步扩展信息,col_id记录的是tid噢~~~
        $dataLandFUnSync = Sync::GetSyncLog($le_trans, 'uu_land_f', $sync_tid, Sync::ORIGIN_16U);
        if (!count($dataLandFUnSync)) {
            exit;
        }
        print_r($dataLandFUnSync);
//        exit;
        foreach ($dataLandFUnSync as $logId=>$row) {
            $sqlId = "SELECT id FROM uu_land_f WHERE tid={$row['sync_id']} LIMIT 1";
            $le->query($sqlId);
            $le->fetch_assoc();
            $land_f_id = $le->f('id');
            if (!$land_f_id) {
                $logWord = "{$date_now}|{$sqlId}|记录不存在";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_land_f_log.log');
                continue;
            }
            $sqlUpdate = "UPDATE uu_land_f SET `{$row['col']}`='{$row['chg_new']}' WHERE id={$land_f_id} LIMIT 1";
            $le->query($sqlUpdate);
//            echo $sqlUpdate . PHP_EOL;
            $logWord = "{$date_now}更新同步票类成功|原始id={$land_f_id},记录主键id=$logId";
            Sync::writeLog($logWord, Sync::LOG_DIR . 'update_land_f.log');
            Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_OK, $land_f_id);
        }
        break;
    case 'update_product':
        $sync_tid       = intval($_REQUEST['tid']);//
        $sync_apply_did = intval($_REQUEST['mid']);//
        $apply_did      = Sync::Auth($sync_apply_did, 1);
        $dataProductsUnSync = Sync::GetSyncLog($le_trans, 'uu_products', $sync_tid, Sync::ORIGIN_16U);
        foreach ($dataProductsUnSync as $logId=>$row) {
            $sqlGetPid = "SELECT pid FROM uu_jq_ticket WHERE sync_id={$row['col_id']} AND apply_did=$apply_did LIMIT 1";
            $le->query($sqlGetPid);
            $le->fetch_assoc();
            $myPid = $le->f('pid');
            if (!$myPid) {
                $logWord = "{$date_now}|{$sqlGetPid}|记录不存在";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_product_log.err');
                continue;
            }
            //票付通平台apply_limit=2为下架先行平台为拒绝。先行平台下架为3
            if ($row['col']=='apply_limit' ) {
                if ($row['chg_new'] == 3 ) {
                    $chg_new = 2;
                } else if($row['chg_new'] == 4) {
                    $chg_new = 1;
                } else {
                    $chg_new = $row['chg_new'];
                }
            }
            elseif ($row['col']=='p_status' && $row['chg_new'] !=6 ) {
                $chg_new = 0;
            }
            else {
                $chg_new = $row['chg_new'];
            }
            $sqlUpdate = "UPDATE uu_products SET `{$row['col']}`='{$chg_new}' WHERE id=$myPid LIMIT 1";
            Sync::writeLog($date_now . '|'.$sqlUpdate, Sync::LOG_DIR . 'sync_product_log.sql');
            if ($le->query($sqlUpdate)) {
                $logWord = "{$date_now}|更新票类成功|原始tid={$row['col_id']},更新ID:{$myPid},记录主键id={$logId}";
                Sync::writeLog($logWord, Sync::LOG_DIR . 'sync_product_log.log');
                Sync::ChgSyncStatus($le_trans, $logId, Sync::SYNC_OK);
            }
        }
        break;
    case 'cancel_sync':
        if (! $_SESSION['memberID']) {
            exit('{"status":"fail", "msg":"登录超时"}');
        }
        $lid = intval($_REQUEST['lid']);
        $res = Sync::CancelSync($_SESSION['memberID'], $lid);
        echo json_encode($res);
        break;
}


